// src/events/events.gateway.ts
import { WebSocketGateway, WebSocketServer, OnGatewayConnection, OnGatewayInit,OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';
import { SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({
  path: '/ws',  // 指定WebSocket路径
  cors: {
    origin: '*', // 生产环境应限制为具体域名
  }
})

export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  private logger = new Logger('WebSocket');

  @WebSocketServer()
  server: Server;

  afterInit(server: Server) {
    this.logger.log('服务器初始化');
  }
  // 基础连接测试
  handleConnection(client: Socket) {

    this.logger.log(`客户端连接: ${client.id}`);
    this.logger.debug(`请求头: ${JSON.stringify(client.handshake.headers)}`);

    const auth = client.handshake.auth; // 获取认证信息
    const token = client.handshake.auth.token;

    // console.log('用户令牌:', token);

    // if (!token) {
    //   throw new Error('未提供认证令牌');
    // }

    console.log('auth.userId:', auth.userId);
    console.log('auth.role:', auth.role);

    let   query = client.handshake.query
   console.log('query.token',query.token); // "your-jwt-token"
   console.log('query.userId',query.userId); // "123"
    client.emit('connection', '成功连接到猫咪咖啡馆实时服务');
  }


  handleDisconnect(client: any) {
    this.logger.log(`客户端断开: ${client.id}`);
  }

  // 猫咪状态变化事件
  @SubscribeMessage('cat-status-change')
  handleCatStatusChange(client: any, payload: { catId: number; status: string }) {
    // 广播给所有客户端
    this.server.emit('cat-status-update', {
      catId: payload.catId,
      status: payload.status,
      updatedAt: new Date(),
    });
  }
}